package com.rescueworkers.adapter;

import java.util.List;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.rescueworkers.R;
import com.rescueworkers.dto.UploadVoiceOrImageInfo;

public class RecordAdapter extends BaseAdapter {
	List<UploadVoiceOrImageInfo> recordInfoList ;
	Context context;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	
	public RecordAdapter(Context context,List<UploadVoiceOrImageInfo> recordInfoList) {
		this.recordInfoList = recordInfoList;
		this.context = context;
	}

	@Override
	public int getCount() {
		return recordInfoList.size();
	}

	@Override
	public Object getItem(int position) {
		return recordInfoList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View view, ViewGroup viewGroup) {
		ViewHolder  holder = null;
		if(view == null){
			holder = new ViewHolder();
			view = LayoutInflater.from(context).inflate(R.layout.record_item, null);
			holder.play = (Button) view.findViewById(R.id.btn_play);
			holder.tvTaskNo = (TextView) view.findViewById(R.id.tv_task_no);
			holder.tvTime = (TextView) view.findViewById(R.id.tv_record_time);
			view.setTag(holder);
		}else{
			holder = (ViewHolder) view.getTag();
		}
		holder.tvTaskNo.setText(recordInfoList.get(position).getNo());
		holder.tvTime.setText(String.valueOf(recordInfoList.get(position).getRecordTime()));
		holder.play.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String recordpath = recordInfoList.get(position).getPath();
				playMusic(recordpath);
			}
		});
		return view;
	}
	
    class ViewHolder{
    	TextView tvTaskNo;
    	TextView tvTime;
    	Button play;
    	
    }
    
    /**
	 * @Description
	 * @param name
	 */
	private void playMusic(String name) {
		try {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
			}
			mMediaPlayer.reset();
			mMediaPlayer.setDataSource(name);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
			mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
				public void onCompletion(MediaPlayer mp) {

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
